import json
import re
from random import choice

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from django.shortcuts import render
from django.views import View

from rest_framework import viewsets, status
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from apps.users.models import VerifyCode
from apps.users.serializers import SmsSerializer, UserRegSerializer
from libs.aliyun import send_sms
from utils import constants

User = get_user_model()


class RegisterView(View):
    def get(self, request):
        return render(request, "register.html")


class LoginView(View):

    def get(self, request):
        return render(request, "login.html")


# class CustomBackend(ModelBackend):
#     """
#     自定义用户认证
#     """
#
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         try:
#             user = User.objects.get(Q(username=username) | Q(mobile=username))  # 获取用户名或手机号，然后判断密码，返回ｕser
#             if user.check_password(password):
#                 return user
#         except Exception as e:
#             return None


class SmsCodeViewset(CreateModelMixin, viewsets.GenericViewSet):
    """
    手机验证码
    """

    serializer_class = SmsSerializer

    def generate_code(self):
        """
        生成四位数字的验证码
        """
        seeds = "1234567890"
        random_str = []
        for i in range(4):
            random_str.append(choice(seeds))

        return "".join(random_str)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        mobile = serializer.validated_data["mobile"]
        print("手机号-------------", mobile)
        code = self.generate_code()
        # -----------------------发送短信验证码－－－－－－－－－－－－－－－－－
        # 模拟发送方式
        # sms_status = send_sms(phone_numbers=mobile, code=code)
        # sms_status = eval(sms_status)
        # print("msg-----------", sms_status["Message"])
        # if sms_status["Message"] != "OK":
        #     return Response({
        #         "mobile": sms_status["Message"]
        #     }, status=status.HTTP_400_BAD_REQUEST)
        print("SMS_Code==", code)
        if not re.match(constants.REGEX_MOBILE, mobile):
            return Response({
                "mobile": "验证码不存在"
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            "验证通过后保存至数据库"
            code_record = VerifyCode(code=code, mobile=mobile)
            code_record.save()
            return Response({
                "mobile": mobile
            }, status=status.HTTP_201_CREATED)


# mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
class UserViewset(CreateModelMixin, viewsets.GenericViewSet):
    """
    用户
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()

    # 验证到类里面
    # authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)

    # def get_serializer_class(self):
    #     if self.action == "retrieve":
    #         return UserDetailSerializer
    #     elif self.action == "create":
    #         return UserRegSerializer
    #
    #     return UserDetailSerializer

    # permission_classes = (permissions.IsAuthenticated, )
    # def get_permissions(self):
    #     if self.action == "retrieve":
    #         return [permissions.IsAuthenticated()]
    #     elif self.action == "create":
    #         return []
    #
    #     return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        print("执行了注册--------------")
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()


from .serializers import LoginAuthSerializer


class LoginAuthorizeView(APIView):

    def post(self, request):
        """
        用户登录:
        1. 获取参数并进行校验
        2. 服务器签发jwt token数据
        3. 返回应答
        """
        # 1. 获取参数并进行校验
        serializer = LoginAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 2. 服务器签发jwt token数据(create)
        serializer.save()

        # 3. 返回应答
        data = serializer.data
        response = Response(data, status=status.HTTP_201_CREATED)
        response.set_cookie("token", data["token"], max_age=60 * 60 * 24)
        response.set_cookie("user", data["username"], max_age=60 * 60 * 24)
        return response

# {'id': 1, 'username': '15658637193',
# 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IjE1Nj'
# 'U4NjM3MTkzIiwiZXhwIjoxNTg2NDQxMTU5LCJlbWFpbCI6bnVsbH0.FrQ2gqnkJQBLBC4D3KzJZaObsINCd'
# 'MNbrJ_4Ad_kCsU'}
